package com.tanger.common.utils;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import com.tanger.common.utils.StringUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQlg工具类
 */
public class SQLUtil {

	/**
	 * 根据数据库连接的URL，取得数据库类型
	 * @param url
	 * @return
	 */
	public static String getDbTypeByUrl(String url) {
		return JdbcUtils.getDbType(url).getDb();
	}

	/**
	 * 取得当前数据源的数据库类型
	 * @return
	 */
	public static String getDbType() {
		return getDbTypeObj().getDb();
	}

	//TODO 默认数据库
	public static DbType getDbTypeObj() {
		return DbType.MYSQL;
	}
	/**
	 * 是否含有sql注入
	 * @param sql sql语句
	 * @return true:含有，false:含有
	 */
	public static boolean containsSqlInjection(String sql) {
		if(StringUtil.isNull(sql)){
			return false;
		}
		Pattern pattern = Pattern.compile("\\b(insert|drop|grant|alter|delete|update|truncate)\\b");
		Matcher matcher = pattern.matcher(sql.toLowerCase());
		return matcher.find();
	}
	/**
	 * 将数据库字段为CLOB的数据转成String
	 * @param clob
	 * @return
	 * @throws SQLException
	 * @throws IOException
	 */
	public static String ClobToString(Clob clob) throws SQLException, IOException {
		String ret = "";
		Reader read= clob.getCharacterStream();
		BufferedReader br = new BufferedReader(read);
		String s = br.readLine();
		StringBuffer sb = new StringBuffer();
		while (s != null) {
			sb.append(s);
			s = br.readLine();
		}
		ret = sb.toString();
		if(br != null){
			br.close();
		}
		if(read != null){
			read.close();
		}
		return ret;
	}
}
